import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd/message';

import {Observable} from 'rxjs';
import {tap, finalize} from 'rxjs/operators';
import {Router} from '@angular/router';
import {Pipe} from '@angular/core';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(private message: NzMessageService, private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();
    let code: number;
    let msg: string;
    const token = localStorage.getItem('token');
    // Get the auth token
    const authToken = token ? token : '';

    // Clone the request and replace the original headers with
    // cloned headers, updated with the token.
    const authReq = req.clone({
      url: 'sola/' + req.url,
      headers: req.headers.set('token', authToken).set('Accept-Language', 'zh-CN')
    });

    // send cloned request with header to the next handler.
    const httpObservable = next.handle(authReq).pipe(
      tap(
        // Succeeds when there is a response; ignore other events
        event => {
          code = event instanceof HttpResponse ? event.body.code : 200;
          msg = event instanceof HttpResponse ? event.body.msg : '系统内部错误';
        },
        // Operation failed; error is an HttpErrorResponse
        error => {
          code = 500;
          msg = '请求出错';
        },
      ),
      // Log when response observable either completes or errors
      finalize(() => {
        const elapsed = Date.now() - started;
        const log = `请求路径:${req.method} ${req.urlWithParams} 返回信息:${msg} 耗时:${elapsed}毫秒  请求参数:${JSON.stringify(req.body)}`;
        if (code === 200 && msg != null && msg !== 'success') {
          this.message.success(msg);
        } else if (code === 401) {
          // token失效过期
          this.message.error(msg);
          this.router.navigateByUrl('login');
        } else if (code !== 200) {
          this.message.error(msg);
        }
        // add operation log
        console.log(log);
      })
    );

    return httpObservable;
  }
}
